package com.drore.cloud.service.impl;

import com.drore.cloud.domain.sys.ImageVerify;
import com.drore.cloud.service.VerifyService;
import com.fasterxml.jackson.databind.ObjectMapper;
import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Coordinate;
import net.coobird.thumbnailator.geometry.Position;
import net.coobird.thumbnailator.geometry.Positions;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.ClassUtils;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Date;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.Semaphore;


@Service("verifyService")
public class VerifyServiceImpl implements VerifyService {


	private final Semaphore permit = new Semaphore(100, true);

	public ImageVerify process(HttpSession session){

		try{
			permit.acquire();
			//业务逻辑处理
			return generate(session);
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			permit.release();
		}
		return null;
	}

	@Override
	public ImageVerify generate(HttpSession session){


		String originalUrl = "C:/Users/Public/Pictures/Sample Pictures/zhuorui.png";
		//originalUrl="http://oss.drore.com/material/e3f9705d09804d7eb790b059f114ecdf/201612/22/df9b0e7ab61f4df9926d795d2f4990c2.jpg";
		originalUrl=getFileName();

		//String alphaUrl = "C:/Users/Public/Pictures/Sample Pictures/zhuorui.png";
		String verifyHome = ClassUtils.getDefaultClassLoader().getResource("").getPath()+"static/img/verify/temp";
		int width = 300;
		int height = 150;
		int repairWidth = 50;
		int repairHeight = 50;
		int wholeItemWidth = 30;
		int wholeItemHeight = 15;
			ImageVerify generate=null;
		try {
			generate = generate(originalUrl, verifyHome, width, height, repairWidth, repairHeight, wholeItemWidth, wholeItemHeight, session);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return generate;
	}

//	@Override
//	public boolean verify(String code,int x,int y,HttpSession session){
//		//boolean result = redisTemplate.hasKey(code);
//		boolean result =session.getAttribute(code)==null;
//		if(result){
//			return true;
//		}
//		return false;
//	}
public  String getFileName() {
	String path = ClassUtils.getDefaultClassLoader().getResource("").getPath()+"static/img/verify/temp/original"; // 路径
	File f = new File(path);
	if (!f.exists()) {
		System.out.println(path + " not exists");
		return "not exists";
	}

	File fa[] = f.listFiles();
	for (int i = 0; i < fa.length; i++) {
		File fs = fa[i];
		if (fs.isDirectory()) {
			System.out.println(fs.getName() + " [目录]");
		} else {
			System.out.println(fs.getName());
		}
	}
	Random random = new Random();
	return  fa[random.nextInt(fa.length)].getPath();
}


	private ImageVerify generate(String originalUrl, String verifyHome
			, int width, int height
			, int repairWidth, int repairHeight
			, int wholeItemWidth, int wholeItemHeight, HttpSession session) throws Exception{
		if(width % wholeItemWidth != 0
				|| height % wholeItemHeight != 0){
			throw new RuntimeException("破图图形错误!");
		}
		Random random = new Random();
		int x_ = random.nextInt(width-repairWidth) % (width-repairWidth*2 + 1) + repairWidth;
		int y_ = random.nextInt(height-repairHeight) % (height-repairHeight*2 + 1) + repairHeight;

		ImageVerify verify = new ImageVerify();
		verify.setInValid(DateUtils.addMinutes(new Date(), 10));
		verify.setOriginal(originalUrl);
		verify.setOffset(10);
		verify.setX(x_);
		verify.setY(y_);
		verify.setVerifyCode(UUID.randomUUID().toString());
		verify.setRepairWidth(repairWidth);
		verify.setRepairHeight(repairHeight);


		/****随便一张大图处理成300*150 ********************************************************************************************************************************/
		String cutName="cut";
		String cutPath = verifyHome + "/cut/" + cutName;
		//补图
		BufferedOutputStream cutOut = new BufferedOutputStream(new FileOutputStream(cutPath));
		// 得到补图
		Thumbnails.of(originalUrl).sourceRegion(Positions.CENTER,300, 150)
				.size(300, 150).keepAspectRatio(true).toOutputStream(cutOut);

		cutOut.flush();
		cutOut.close();
		verify.setOriginal(cutPath);
		/*********切下来那块图***************************************************************************************************************************/
		String repairName = UUID.randomUUID().toString();
		repairName="QIEXIALAI";
		String repairPath = verifyHome + "/repair/" + repairName;
		//补图
		BufferedOutputStream repairOut = new BufferedOutputStream(new FileOutputStream(repairPath));
		// 得到补图
		Thumbnails.of(verify.getOriginal()).sourceRegion((int)verify.getX(),(int)verify.getY(),repairWidth, repairHeight)
				.size(repairWidth, repairHeight).keepAspectRatio(true).toOutputStream(repairOut);

		repairOut.flush();
		repairOut.close();




		/************************************************************************************************************************************/
		//空缺图
		//String vacancyName = UUID.randomUUID().toString();
		String vacancyName="KONGQUETU";
		String vacancyPath = verifyHome + "/vacancy/" + vacancyName;
		BufferedOutputStream vacancyOut = new BufferedOutputStream(new FileOutputStream(vacancyPath));
		int x1 = verify.getX();
		int y1 = verify.getY();
		// 得到空缺图
		BufferedImage imageNew111 = new BufferedImage(50,50,BufferedImage.TYPE_INT_RGB);


		ByteArrayOutputStream os = new ByteArrayOutputStream();
		ImageIO.write(imageNew111,"png",os);
		BufferedImage watermarkImage = ImageIO.read(os.toInputStream());
		Position point = new Coordinate(x1, y1);
		BufferedImage whole = Thumbnails.of(verify.getOriginal())
				.watermark(point, watermarkImage, 0.65f)
				.outputQuality(1)//生成质量100%
				.scale(1)//缩放比例
				.asBufferedImage();

		ImageIO.write(whole, "png", vacancyOut);
		vacancyOut.flush();
		vacancyOut.close();
/************************************************************************************************************************************/

		verify.setWhole(vacancyPath);
		verify.setRepair(repairPath);

		session.setAttribute(verify.getVerifyCode(),x_);
		verify.setX(0);
		return verify;
	}

	private static class JsonUtil{
		private final static ObjectMapper objectMapper = new ObjectMapper();

		public static <T> T json2pojo(String jsonStr, Class<T> clazz)  throws Exception {
			return objectMapper.readValue(jsonStr, clazz);
		}

		public static String obj2json(Object obj) throws Exception {
			return objectMapper.writeValueAsString(obj);
		}
	}



}
